package cn.demomaster.quickui.view.banner;

import static android.view.View.VISIBLE;
import static cn.demomaster.quickui.view.banner.BannerContentType.img;
import static cn.demomaster.quickui.view.banner.BannerContentType.video;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.io.File;

import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quickui.helper.cache.CacheInfo;
import cn.demomaster.quickui.helper.cache.QuickCache;
import cn.demomaster.quickui.helper.cache.UrlHelper;
import cn.demomaster.quickui.view.banner.qdlayout.QdVideo;

/**
 * 广告轮播单条信息流
 */
public abstract class BannerFragment extends Fragment implements BannerFragmentInterface {
    AdsResource adsResource;
    BannerFragmentStateAdapter.OnPlayingListener mOnloadingListener;
    FragmentHander fragmentHander;

    public BannerFragment() {
    }

    public BannerFragment(AdsResource adsResource, BannerFragmentStateAdapter.OnPlayingListener onloadingListener,FragmentHander fragmentHander) {
        this.adsResource = adsResource;
        this.mOnloadingListener = onloadingListener;
        this.fragmentHander = fragmentHander;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        QdLog.d("onHiddenChanged=" + this.getClass().getSimpleName() + ",hidden=" + hidden);
    }
    int fragmentIndex;
    @Override
    public void setArguments(@Nullable Bundle args) {
        super.setArguments(args);
        if(args!=null){
            if(args.containsKey("FragmentIndex")){
                fragmentIndex = args.getInt("FragmentIndex");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //QdLog.d("fragment["+fragmentIndex+"] =>"+hashCode()+" onresume");
        onActiveChanged(this.hashCode());
    }

    private void loadResource() {
        BannerFileType adsResourceType = BannerFileType.getEnum(adsResource.getFrom());
        //QdLog.i("fragment[" + fragmentCode + "] =>"+hashCode()+" 加载数据,类型：" + BannerContentType.getEnum(adsResource.getType())+","+adsResourceType);
        switch (adsResourceType) {
            case local://本地资源
                //QdLog.i("本地资源 >> "+fragmentCode);
                resetView();
                break;
            case remote://网络资源
                loadRemoteResource();
                break;
        }
    }

    /**
     * 加载本地资源
     */
    private void activeFragment() {

    }

    /**
     * 加载网络资源
     */
    private void loadRemoteResource() {
        //QdLog.i("loadRemoteResource >> "+fragmentCode);
        //获取url类型
        final String urlString = adsResource.getUrl();
        if (QuickCache.enable() && QuickCache.containsKey(urlString)) {
            CacheInfo fileInfo = QuickCache.getCacheInfoByKey(urlString);
            if (fileInfo != null) {
                if (!TextUtils.isEmpty(fileInfo.getFilePath())) {
                    adsResource.setFrom(BannerFileType.local.value());
                    adsResource.setFilePath(fileInfo.getFilePath());
                    adsResource.setType(getFileType(fileInfo.getFileType()));
                   // System.out.println("从缓存中获取 " + fileInfo.getFileType() + "," + fileInfo.getFilePath());
                    resetView();
                    return;
                } else {
                 //   System.out.println("缓存文件路徑不存在: " + urlString);
                }
            } else {
               // System.out.println("缓存中不存在2: " + urlString);
            }
        } else {
            //System.out.println("缓存中不存在1: " + urlString);
        }

        UrlHelper.analyUrl(urlString, new UrlHelper.AnalyResult() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void success(String url, String fileType, int fileLength) {
                //QdLog.println(" " + fragmentCode + ",网络资源类型：" + fileType + ",当前类型：" + BannerContentType.getEnum(adsResource.getType()));
                if (adsResource.getType() != getFileType(fileType)) {
                    QuickCache.addFile(urlString, fileType, null);
                    adsResource.setType(getFileType(fileType));
                    if (adsResource.getType() == video.value()) {
                        QuickCache.downCacheFile(urlString,urlString, fileType);
                    }
                }
                resetView();
            }

            @Override
            public void error() {

            }
        });
    }

    public int getFileType(String fileType) {
        if (fileType.startsWith("image/")) {
            return img.value();
        } else if (fileType.startsWith("video/")) {
            return video.value();
        }
        return -1;
    }

    /**
     * 重置布局
     */
    private void resetView() {
        QdLog.d("resetView >> "+fragmentIndex);

        BannerContentType resourceType = BannerContentType.getEnum(adsResource.getType());
        if (resourceType == null) {
            QdLog.println("[" + fragmentIndex + "] resourceType =null ");
            return;
        }
        releaseUnUsedView(resourceType);
        QdLog.d("fragmentIndex="+fragmentIndex+",getCurrentItem="+fragmentHander.getCurrentItem());
        if (fragmentIndex == fragmentHander.getCurrentItem()) {
            activeFragment();
        }
    }


    /**
     * 移除无用控件
     * @param resourceType
     */
    private void releaseUnUsedView(BannerContentType resourceType) {
        switch (resourceType) {
            case video:

                break;
        }
        BannerContentType[] enumArray = BannerContentType.values();
        for (BannerContentType bannerContentType : enumArray) {
            if (bannerContentType != resourceType) {
                releaseUnUsedView2(bannerContentType);
            }
        }
    }

    private void releaseUnUsedView2(BannerContentType resourceType) {
        switch (resourceType) {
            case text:
            case html:
                break;
            case video:
                break;
            case img:
                break;
        }
    }

    /*
        void loading();
        void complete();
        void error();*/
    boolean isActived;

    @Override
    public void onActiveChanged(int activedHash) {
        //QdLog.i("状态变化 " + fragmentCode + "=> " + hashCode() +"=?"+activedHash);

    }

    @Override
    public void onPause() {
        super.onPause();
        pause();
    }

    @Override
    public void onDestroyView() {
        pause();
        super.onDestroyView();
        if(fragmentHander!=null){
            fragmentHander=null;
        }
        if(mOnloadingListener!=null){
            mOnloadingListener = null;
        }
    }

    @Override
    public void onDetach() {
//        if (adsAdapter != null) {
//            adsAdapter.unregisterFragment(this.hashCode());
//        }
        super.onDetach();
    }

    /**
     * 页面暂停播放，
     */
    public void pause() {
       /* if(fragmentCode!=-1) {
            QdLog.i("fragment[" + fragmentCode + "] =>"+hashCode()+" 暂停 " + hashCode());
        }*/
    }

}